<template>
  <div>

    <!--搜索-->
    <div style="margin: 10px 0">
      <el-input v-model="name" placeholder="请输入名称" style="width: 200px" suffix-icon="el-icon-search"
                clearable></el-input>
      <el-button type="primary" style="margin-left: 5px" @click="load">搜索</el-button>
      <el-button type="warning" style="margin-left: 5px" @click="reset">重置</el-button>
    </div>
    <!--编辑-->
    <div style="margin: 10px 0">
      <el-button type="primary" @click="handAdd">新增 <i class="el-icon-circle-plus-outline"></i></el-button>
      <el-popconfirm
          class="ml-5 mr-5"
          confirm-button-text='我已经下定了决心'
          cancel-button-text='不，不要。不要啊'
          icon="el-icon-info"
          icon-color="red"
          title="这可是一堆数据哥们，好好思考一下？"
          @confirm="delBatch"
      >
        <el-button type="danger" slot="reference">批量删除 <i class="el-icon-remove-outline"></i></el-button>
      </el-popconfirm>
    </div>
    <!--          表格数据-->
    <el-table :data="tableData" border stripe @selection-change="handleSelectionChange"
              :header-cell-style="{background:'#eef1f6',color:'#606266'}">
      <el-table-column
          type="selection"
          width="55">
      </el-table-column>
      <el-table-column label="ID" prop="id" width="80"></el-table-column>
      <el-table-column label="名称" prop="name"></el-table-column>
      <el-table-column label="唯一标识" prop="flag"></el-table-column>
      <el-table-column label="描述" prop="description"></el-table-column>
      <el-table-column label="操作" prop="handle" width="300px">
        <template #default="scope">
          <el-button type="info" @click="selectMenu(scope.row)">分配菜单 <i class="el-icon-menu"></i></el-button>
          <el-button type="success" @click="handEdit(scope.row)">编辑 <i class="el-icon-edit"></i></el-button>
          <el-popconfirm
              class="ml-5"
              confirm-button-text='确认删除'
              cancel-button-text='我再想想'
              icon="el-icon-info"
              icon-color="red"
              title="Are you Sure？"
              @confirm="handDelete(scope.row.id)"
          >
            <el-button type="danger" slot="reference">删除 <i class="el-icon-delete"></i>
            </el-button>
          </el-popconfirm>
        </template>
      </el-table-column>

    </el-table>
    <!--          分页-->
    <div class="demo-pagination-block" style="padding: 10px 0">
      <el-pagination
          :current-page="currentPage"
          :page-size="pageSize"
          :page-sizes="[5, 10, 15, 20]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      />
    </div>
    <div>
      <el-dialog title="角色信息" :visible.sync="dialogFormVisible" width="30%">
        <el-form :model="form" label-width="80px" size="small">
          <el-form-item label="名称">
            <el-input v-model="form.name" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="唯一标识">
            <el-input v-model="form.flag" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="描述">
            <el-input v-model="form.description" autocomplete="off"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="save">确 定</el-button>
        </div>
      </el-dialog>

      <el-dialog title="菜单分配" :visible.sync="menuDialogVis" width="30%">
        <el-form :model="form" label-width="80px" size="small">
<!--          :check-strictly="true"-->
          <el-tree

              :props="props"
              :data="menuData"
              show-checkbox
              node-key="id"
              ref="tree"
              :default-expanded-keys="expends"
              :default-checked-keys="checks"
          >
             <span class="custom-tree-node" slot-scope="{ node, data }">
               <span><i :class="data.icon"/> {{ data.name }}</span>
             </span>
          </el-tree>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="menuDialogVis = false">取 消</el-button>
          <el-button type="primary" @click="saveRoleMenu">确 定</el-button>
        </div>
      </el-dialog>
    </div>
    <!--          弹窗-->
  </div>
</template>

<script>
export default {
  name: "User",
  data() {
    return {
      tableData: [],
      currentPage: 1,
      pageSize: 5,
      total: 0,
      name: '',
      form: {},
      dialogFormVisible: false,
      menuDialogVis: false, // 菜单分配弹窗
      multipleSelection: [],
      menuData: [],
      props: {
        label: 'name',
      },
      expends: [],
      checks: [],
      roleId: 0,
      roleFlag: ''
    }
  },
  created() {
    this.load()
  },
  methods: {
    load() {
      this.request.get("/role/page", {
        params: {
          pageNum: this.currentPage,
          pageSize: this.pageSize,
          name: this.name,
        }
      }).then(res => {
        // console.log(res);
        this.tableData = res.data.records
        this.total = res.data.total
      })
    },
    reset() {
      this.name = ''
      this.load()

    },
    handAdd() {
      this.dialogFormVisible = true
      this.form = {}
    },
    save() {
      this.request.post("/role", this.form).then(res => {
        if (res.code === '200') {
          this.$message.success("保存成功")
          this.dialogFormVisible = false;
          this.load()
        } else {
          this.$message.error("保存失败")
        }
      })
    },
    saveRoleMenu() {
      console.log(this.$refs.tree.getCheckedKeys());
      this.request.post("/role/roleMenu/" + this.roleId, this.$refs.tree.getCheckedKeys()).then((res) => {
        // console.log(res);
        if (res.code === '200') {
          this.$message.success("绑定成功")
          this.menuDialogVis = false
          // 操作管理员角色后需要重新登录
          if (this.roleFlag === 'ROLE_ADMIN'){
            this.$store.commit("logout")
          }
        } else {
          this.$message.error("绑定失败")
        }
      })
    },
    handEdit(row) {
      this.form = row
      this.dialogFormVisible = true
      this.form = Object.assign({}, row) //点击取消后不保存数据 其实就是拷贝到一个空对象，就得到了原始对象的克隆，不进行修改，返回原来的对象
    },
    handDelete(id) {
      this.request.delete("/role/" + id).then((res) => {
        if (res.code === '200') {
          this.$message.success("删除成功")
          this.load()
        } else {
          this.$message.error("删除失败")
        }
      })
    },
    handleSelectionChange(val) {
      console.log(val); //val是一个对象
      this.multipleSelection = val
    },
    delBatch() {
      let ids = this.multipleSelection.map(value => value.id) // [{},{}] => [1,2...]
      this.request.post("/role/del/batch", ids).then((res) => {
        if (res.code === '200') {
          this.$message.success("批量删除成功")
          this.load()
        } else {
          this.$message.error("删除失败")
        }
      })
    },
    handleSizeChange(pageSize) {
      console.log(pageSize);
      this.pageSize = pageSize
      this.load()
    },
    handleCurrentChange(pageNum) {
      console.log(pageNum);
      this.currentPage = pageNum
      this.load()
    },
    selectMenu(role) {
      this.menuDialogVis = true
      this.roleId = role.id
      this.roleFlag = role.flag
      // 请求菜单数据
      this.request.get("/menu").then(res => {
        this.menuData = res.data
        // 把后台返回的菜单数据处理成id数组
        this.expends = this.menuData.map(value => value.id)
      })
      this.request.get("/role/roleMenu/" + this.roleId).then(res => {
        this.checks = res.data

        this.request.get("/menu/ids").then((r) => {
          const ids = r.data
          ids.forEach(id => {
            if(!this.checks.includes(id)){
              this.$refs.tree.setChecked(id,false,false )
            }
          })
        })
        this.menuDialogVis = true
      })
    },

  }
}
</script>

<style scoped>

</style>